<?php
/**
 * (logic) 返款
 */
namespace App\Logic\MonthlyReportLT;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysICountry;
use App\Models\MonthlyReportLT\Cost\LogisticsBasics;
use App\Models\MonthlyReportCommon\Cost\PriceBasics;
use App\Models\MonthlyReportLT\Payment\PaymentOrder;
use App\Models\Reimburse\ReimburseDetail;
use Illuminate\Support\Facades\DB;
class CalculateReimburse
{
    /**
     * 刷单费用计算：
     * 1.订单类型：
     * 情况1.未匹配到订单：
     * 支付金额+采购成本+运费成本
     * 情况2.能匹配到订单：
     * 情况1.AFN   支付金额+采购成本+运费成本-收款费用
     * 情况2.MFN  支付金额-收款费用
     * 2.非订单类型：
     * 刷单费用 = 支付金额
     */
    public static function exe()
    {
        $date = date('Y-m-01',strtotime('midnight first day of -1 month'));
        try{
            DB::beginTransaction();
            $area = [];
            $rate = [];
            ReimburseDetail::query()->where('paid_status',3)
                ->where('report_date',$date)
                ->select('id','reimburse_no','fee_type','order_no','country_id','psku_id','currency_code','rate_odds','paid_amount_1',
                    'paid_amount_2','paid_amount_3','currency_code_4','rate_odds_4','paid_amount_4','paid_date','paid_date_4')
                ->orderBy('id')
                ->chunk(100, function ($items)use (&$area,&$rate,$date){
                    $sql = "UPDATE reimburse_detail SET ";
                    $idArr = [];
                    $sql1 = "r_rate_odds = CASE id ";
                    $sql2 = "r_currency_code = CASE id ";
                    $sql3 = "r_amount = CASE id ";
                    $sql4 = "fulfillment_type = CASE id ";
                    $sql5 = "purchase_price_rmb = CASE id ";
                    $sql6 = "shipment_price_rmb = CASE id ";
                    $sql7 = "amount_rmb = CASE id ";
                    $sql8 = "rate_odds = CASE id ";
                    $sql9 = "rate_odds_4 = CASE id ";
                    $sql10 = "r_amount_rmb = CASE id ";
                    foreach ($items as $item){
                        if($item->currency_code){
                            $at = strtotime($item->paid_date);
                            $rateOdds = ExchangeRate::getRateOddsToRMB($item->currency_code,$at);
                        }else{
                            $rateOdds = $item->rate_odds;
                        }
                        if($item->currency_code_4){
                            $at4 = strtotime($item->paid_date_4);
                            $rateOdds4 = ExchangeRate::getRateOddsToRMB($item->currency_code_4,$at4);
                        }else{
                            $rateOdds4 = $item->rate_odds_4;
                        }
                        $paidAmountRMB = self::_getPaidAmountRMB($rateOdds,$item->paid_amount_1,$item->paid_amount_2,$item->paid_amount_3,$rateOdds4,$item->paid_amount_4);
                        if($item->fee_type == 1){
                            if(!array_key_exists($item->country_id,$area)){
                                $area[$item->country_id] = SysICountry::getAreaIdByCountryId($item->country_id);
                            }
                            $areaId = $area[$item->country_id];
                            $po = self::_getPaymentOrder($item->country_id,$item->order_no);
                            if(!$po){
                                $purchasePrice = PriceBasics::getPrice($item->psku_id,$date);
                                $shipmentFee = LogisticsBasics::getLogistics($areaId,$item->psku_id,$date);
                                $brushAmountRMB = round($paidAmountRMB + $purchasePrice + $shipmentFee,3);
                                $sql1 .= sprintf("WHEN %d THEN %0.4f ", $item->id, 0);
                                $sql2 .= sprintf("WHEN %d THEN %s ", $item->id, 'null');
                                $sql3 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                                $sql4 .= sprintf("WHEN %d THEN %s ", $item->id, 'null');
                                $sql5 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $purchasePrice);
                                $sql6 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $shipmentFee);
                                $sql7 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $brushAmountRMB);
                                $sql8 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds);
                                $sql9 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds4);
                                $sql10 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                            }else{
                                $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($item->country_id);
                                if(!array_key_exists($item->country_id,$rate)){
                                    $at0 = strtotime($date);
                                    $rate[$item->country_id] = ExchangeRate::getRateOddsToRMB($currencyCode,$at0);
                                }
                                $rRateOdds = $rate[$item->country_id];
                                if($po->fulfillment_type == 1){
                                    $purchasePrice = PriceBasics::getPrice($item->psku_id,$date);
                                    $shipmentFee = LogisticsBasics::getLogistics($areaId,$item->psku_id,$date);
                                }else{
                                    $purchasePrice = 0;
                                    $shipmentFee = 0;
                                }
                                $rAmountRMB = round($po->total * $rRateOdds,3);
                                $brushAmountRMB = round($paidAmountRMB - $rAmountRMB + $purchasePrice + $shipmentFee,3);
                                $sql1 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rRateOdds);
                                $sql2 .= sprintf("WHEN %d THEN %s ", $item->id, "'".$currencyCode."'");
                                $sql3 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $po->total);
                                $sql4 .= sprintf("WHEN %d THEN %d ", $item->id, $po->fulfillment_type);
                                $sql5 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $purchasePrice);
                                $sql6 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $shipmentFee);
                                $sql7 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $brushAmountRMB);
                                $sql8 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds);
                                $sql9 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds4);
                                $sql10 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $rAmountRMB);
                            }
                        }else{
                            $sql1 .= sprintf("WHEN %d THEN %0.4f ", $item->id, 0);
                            $sql2 .= sprintf("WHEN %d THEN %s ", $item->id, 'null');
                            $sql3 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                            $sql4 .= sprintf("WHEN %d THEN %s ", $item->id, 'null');
                            $sql5 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                            $sql6 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                            $sql7 .= sprintf("WHEN %d THEN %0.3f ", $item->id, $paidAmountRMB);
                            $sql8 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds);
                            $sql9 .= sprintf("WHEN %d THEN %0.4f ", $item->id, $rateOdds4);
                            $sql10 .= sprintf("WHEN %d THEN %0.3f ", $item->id, 0);
                        }
                        $idArr[] = $item->id;
                    }
                    $ids = implode(',',$idArr);
                    $sql1 .= "END,";
                    $sql2 .= "END,";
                    $sql3 .= "END,";
                    $sql4 .= "END,";
                    $sql5 .= "END,";
                    $sql6 .= "END,";
                    $sql7 .= "END,";
                    $sql8 .= "END,";
                    $sql9 .= "END,";
                    $sql10 .= "END";
                    $sql .= $sql1 . $sql2 . $sql3 . $sql4 . $sql5 . $sql6 . $sql7 . $sql8 . $sql9 . $sql10 . " WHERE id IN ($ids)";
                    DB::update(DB::raw($sql));
            });
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 支付金额RMB
     * @param $rateOdds
     * @param $paidAmount1
     * @param $paidAmount2
     * @param $paidAmount3
     * @param $rateOdds4
     * @param $paidAmount4
     * @return float
     */
    private static function _getPaidAmountRMB($rateOdds,$paidAmount1,$paidAmount2,$paidAmount3,$rateOdds4,$paidAmount4){
        return round(($rateOdds ?: 0) * (($paidAmount1 ?: 0) + ($paidAmount2 ?: 0) + ($paidAmount3 ?: 0)) + ($rateOdds4 ?: 0) * ($paidAmount4 ?: 0),3);
    }

    /**
     * 获取收款订单
     * @param $countryId
     * @param $orderId
     * @return mixed
     */
    private static function _getPaymentOrder($countryId,$orderId){
        return PaymentOrder::query()->where('country_id',$countryId)->where('order_id',$orderId)->first();
    }
}
